import { routes } from '@/router';
import dayjs from 'dayjs';
/**
 * 序列化object数据，用于url带参数跳转
 *
 * @param {(Record<string, string | number | boolean>)} object
 * @param {string} [prefix='?']
 * @returns {*}
 */
const stringifyData = (object : Record<string, string | number | boolean>, prefix = '?') => {
	return Object.keys(object).reduce((pre, cur, index) => {
		pre += `${index !== 0 ? '&' : ''}${cur}=${object[cur]}`;
		return pre;
	}, prefix);
};

export function sleep(time : number) {
	return new Promise((resolve) => {
		setTimeout(() => {
			resolve(true);
		}, time);
	});
}

export function navigateTo(url : string) {
	if (!url.length) {
		return;
	}
	let path = url;
	if (!url.startsWith('/')) {
		path = '/' + path;
	}
	uni.navigateTo({ url: path });
}

export function redirectTo(url : string) {
	if (!url.length) {
		return;
	}
	let path = url;
	if (!url.startsWith('/')) {
		path = '/' + path;
	}
	uni.redirectTo({ url: path });
}

/**
 * 路由的name方式跳转，带参
 *
 * @export
 * @param {string} name
 * @param {?(Record<string, string | number | boolean>)} [data]
 */
export function navigateNameTo(name : string, data ?: Record<string, string | number | boolean>) {
	if (!name.length) {
		return;
	}
	const url =
		'/' +
		routes[name] +
		(data ? stringifyData(data as Record<string, string | number | boolean>) : '');
	console.log('执行name跳转', url);

	uni.navigateTo({ url });
}
/**
 * 路由的name方式redirect跳转
 *
 * @export
 * @param {string} name
 * @param {?(Record<string, string | number | boolean>)} [data]
 */
export function redirectNameTo(name : string, data ?: Record<string, string | number | boolean>) {
	console.log('执行name跳转', data);
	if (!name.length) {
		return;
	}
	const url =
		'/' +
		routes[name] +
		(data ? stringifyData(data as Record<string, string | number | boolean>) : '');
	uni.redirectTo({ url });
}

/**
 * 获取特定格式的格式时间
 *
 * @param {?Date} [date]
 * @returns {*}
 */
export const formatDate = (date ?: number | string, format = 'YYYY-MM-DD') : string => {
	const _date = date || new Date();
	return dayjs(_date).format(format);
};

/**
 * 是否是合法的手机号
 */
export const isPhone = (phone : number) => {
	return /^[1][3,4,5,7,8,9][0-9]{9}$/.test(phone)
}